package com.jxbeidou.system.menu.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import com.jxbeidou.core.entity.PageResult;
import com.jxbeidou.core.mybatis.service.impl.BaseServiceImpl;
import com.jxbeidou.core.mybatis.convert.PageResultConvert;
import com.jxbeidou.system.menu.convert.PermissionConvert;
import com.jxbeidou.system.menu.entity.PermissionDO;
import com.jxbeidou.system.menu.query.PermissionQuery;
import com.jxbeidou.system.menu.vo.PermissionVO;
import com.jxbeidou.system.menu.mapper.PermissionMapper;
import com.jxbeidou.system.menu.service.PermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 菜单表
 *
 * @author 杜晓祥 
 * @since 1.0.0 2023-12-14
 */
@Service
@AllArgsConstructor
public class PermissionServiceImpl extends BaseServiceImpl<PermissionMapper, PermissionDO> implements PermissionService {

    @Override
    public PageResult<PermissionVO> page(PermissionQuery query) {
        IPage<PermissionDO> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        PageResult<PermissionVO> result = PageResultConvert.convert(page, entityList -> PermissionConvert.INSTANCE.convertList(entityList));
        return result;
    }

    private LambdaQueryWrapper<PermissionDO> getWrapper(PermissionQuery query){
        LambdaQueryWrapper<PermissionDO> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(query.getName()), PermissionDO::getName, query.getName());
        wrapper.eq(StringUtils.isNotEmpty(query.getIcon()), PermissionDO::getIcon, query.getIcon());
        wrapper.eq(query.getParentId() != null, PermissionDO::getParentId, query.getParentId());
        wrapper.eq(query.getType() != null, PermissionDO::getType, query.getType());
        wrapper.eq(query.getStatus() != null, PermissionDO::getStatus, query.getStatus());
        return wrapper;
    }

    @Override
    public void save(PermissionVO vo) {
        PermissionDO entity = PermissionConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(PermissionVO vo) {
        PermissionDO entity = PermissionConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public List<PermissionDO> selectByUserId(Long userId) {
        return this.baseMapper.selectByUserId (userId);
    }
}